package com.bl.student.service.biz.message.impl;


import com.bl.student.common.template.PushMessageTemplate;
import com.bl.student.dao.model.UserEntity;
import com.bl.student.dao.redis.UserInfoDao;
import com.bl.student.dao.redis.model.UserInfo;
import com.bl.student.dao.repository.UserRepository;
import com.bl.student.service.biz.message.PushMessageService;
import com.bl.student.tp.getui.GetuiPayloadContent;
import com.bl.student.tp.getui.push.GetuiPushApi;
import com.bl.student.tp.getui.push.GetuiPushRequest;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yujingyi on 2017/9/7.
 */
@Service
@Log4j2
public class PushMessageServiceImpl implements PushMessageService {

    @Autowired
    GetuiPushApi getuiPushApi;

    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    UserRepository userRepository;

    public void pushMessage(PushMessageTemplate pushMessageTemplate) {

        List<UserEntity> userList  = userRepository.findAll();

        List<String> accountList = new ArrayList<>();

        for (UserEntity user : userList) {
            accountList.add(user.getMobile());
        }

        for (String account : accountList) {
            Optional<UserInfo> userInfoOptional = userInfoDao.getUserInfo(account);

            if (!userInfoOptional.isPresent() || Strings.isNullOrEmpty(userInfoOptional.get().getCId())) {
                continue;
            }

            UserInfo userInfo = userInfoOptional.get();

            GetuiPayloadContent getuiPayloadContent = GetuiPayloadContent.builder()
                    .action(pushMessageTemplate.getAction().getType())
                    .content(pushMessageTemplate.getContent())
                    .module(pushMessageTemplate.getModule().getModule())
                    .title(pushMessageTemplate.getTitle())
                    .num("1")
                    .build();


            GetuiPushRequest getuiPushRequest = GetuiPushRequest.builder()
                    .title(pushMessageTemplate.getTitle())
                    .content(pushMessageTemplate.getContent())
                    .cid(userInfo.getCId())
                    .payloadContent(getuiPayloadContent)
                    .build();

            getuiPushApi.pushMessage(getuiPushRequest);
        }
    }
}
